/**
 * 
 */
package com.josian.twittermining.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import com.google.gson.Gson;
import com.josian.twittermining.model.Search;

/**
 * @author josian
 *
 */
public class RequestManager {

	private static final String API_SEARCH_URL = "http://search.twitter.com/search.json?q=";
	
	private static final String HTTP_METHOD = "GET";
	
	
	public static Search performSearchRequest(String keyWord) {
		Search s = null;
		URL url = null;
		HttpURLConnection connection = null;
		BufferedReader rd = null;
		StringBuilder sb = null;
		String line = null;
		
		try {
			
			url = new URL(API_SEARCH_URL.concat(keyWord));
			connection = (HttpURLConnection) url.openConnection();
			connection.setRequestMethod(HTTP_METHOD);
			
			connection.connect();
			
			//read the result from the server
			rd  = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			sb = new StringBuilder();
			
			while ((line = rd.readLine()) != null)
			{
			    sb.append(line + '\n');
			}
			
			Gson gson = new Gson();
			
			s = gson.fromJson(sb.toString(), Search.class);
			
			
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return s;
	}
}
